﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;

namespace SistemaAcademicoDAL
{
    public class Connection
    {
        private SqlConnection conexao;
        private string conn;

        public string ConnectionString
        {
            get { return conn; }
            set { conn = value; }
        }

        public Connection()
        {
        }

        public Connection(string connectionString)
        {
            ConnectionString = connectionString;
        }

        public void OpenConnection()
        {
            if (String.IsNullOrEmpty(ConnectionString))
            {
                throw new Exception("Não foi informada a String de Conexão");
            }
            else
            {
                if (conn != null)
                {
                    conexao = new SqlConnection();
                    conexao.ConnectionString = conn;
                }

                conexao.Open();
            }
        }

        public void CloseConnection()
        {
            if (conexao != null && conexao.State == ConnectionState.Open)
            {
                conexao.Close();
            }
        }

        public IDataReader RetrieveData(string sql)
        {
            if (String.IsNullOrEmpty(sql))
            {
                throw new Exception("Não foi informado a QUERY SQL.");
            }

            if ((conexao == null) || (conexao.State == ConnectionState.Closed))
            {
                throw new Exception("A conexão está fechada");
            }

            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.Connection = conexao;
            sqlCommand.CommandText = sql;
            IDataReader reader = sqlCommand.ExecuteReader();

            return reader;
        }

        public int ExecuteCommand(string sql)
        {
            if (String.IsNullOrEmpty(sql))
            {
                throw new Exception("Não foi informado a QUERY SQL.");
            }

            if ((conexao == null) || (conexao.State == ConnectionState.Closed))
            {
                throw new Exception("A conexão está fechada");
            }

            SqlCommand sqlCommand = new SqlCommand();
            sqlCommand.Connection = conexao;
            sqlCommand.CommandText = sql;
            int result = sqlCommand.ExecuteNonQuery();

            return result;
        }

        public SqlConnection GetSQLConnection()
        {
            return conexao;
        }



    }//class
}//namespace
